#include "date.h"

int getYearMonth(int year, int month)
{
	assert(month > 1 || month < 13);
	int days[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };

	// 判断当前年份是否为闰年，以确定2月份的天数
	if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))
	{
		return 29;
	}

	return days[month];
}

Date& Date::operator += (int day)
{
	_day += day;
	while (_day > getYearMonth(_year, _month))
	{
		_day -= getYearMonth(_year, _month);
		++_month;
		if (13 == _month)
		{
			++_year;
			_month = 1;
		}
	}

	return *this;
}

Date Date::operator + (int day) const
{
	Date tmp = (*this);
	tmp += day;
	return tmp;
}

Date& Date::operator -= (int day)
{
	_day -= day;
	while (_day <= 0)
	{
		_day += getYearMonth(_year, _month);
		--_month;
		if (0 == _month)
		{
			--_year;
			_month = 12;
		}
	}
	return *this;
}

Date Date::operator - (int day) const
{
	Date tmp = (*this);
	tmp -= day;
	return tmp;
}

int Date::operator  - (const Date& d) const
{
	Date max = (*this);
	Date min = d;
	int flag = 1;

	if (max < min)
	{
		max = d;
		min = (*this);
		flag = -1;
	}

	int n = 0;
	while (max != min)
	{
		++min;
		++n;
	}
	return n * flag;
}

Date& Date::operator ++ ()
{
	*this += 1;
	return *this;
}

Date Date::operator ++ (int) // 后置++ -参数列表里的int没有实际用途仅仅是为了占位，主要是区别于前置++函数，构成函数重载
{
	Date tmp(*this);
	(*this) += 1;
	return tmp;

}

Date& Date::operator -- ()   // 前置--
{
	(*this) -= 1;
	return (*this);
}

Date Date::operator -- (int) // 后置--
{
	Date tmp(*this);
	(*this) -= 1;
	return tmp;
}


bool Date::operator == (const Date& d) const
{
	return _year == d._year && _month == d._month && _day == d._day;
}

bool Date::operator != (const Date& d) const
{
	return !(*this == d);
}

bool Date::operator < (const Date& d) const
{
	if (_year < d._year)
	{
		return true;
	}
	else if (_year == d._year && _month < d._month)
	{
		return true;
	}
	else if (_year == d._year && _month < d._month && _day < d._day)
	{
		return true;
	}
	else
	{
		return false;
	}
}

bool Date::operator <= (const Date& d) const
{
	return (*this < d) || (*this == d);
}

bool Date::operator > (const Date& d) const
{
	return !(*this <= d);
}

bool Date::operator >= (const Date& d) const
{
	return (*this > d) || (*this == d);
}
